<template>
  <!-- 登录界面，此处写html结构 -->
  <div class="login_container">
    <div class="login_box">
      <!-- 登录表单区域 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules">
        <el-form-item prop="phone">
          <el-input
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone-outline"
            v-model="loginForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            v-model="loginForm.password"
            show-password
          ></el-input>
        </el-form-item>
        <span @click="showLoginDialog">忘记密码 ?</span>
        <el-form-item class="btns">
          <el-button type="primary" round @click="login">登录</el-button>
          <el-button type="success" round @click="register">注册</el-button>
          <el-button type="info" round @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog
      title="验证码登录"
      :visible.sync="dialogVisible"
      width="40%"
      @close="captchaDialogClosed"
    >
      <el-form
        :model="captchaLoginForm"
        :rules="loginRules"
        ref="captchaLoginFormRef"
        label-width="80px"
      >
        <el-form-item label="手机号码" prop="phone">
          <el-input
            v-model="captchaLoginForm.phone"
            placeholder="请输入您的手机号码"
          >
            <template slot="append">
              <el-button @click="sendCaptcha">发送验证码</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input
            v-model="captchaLoginForm.captcha"
            :disabled="captchaLoginForm.whether"
            placeholder="请输入您的验证码"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="captchaLogin">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    var checkPhone = (rule, value, callback) => {
      const regPhone =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regPhone.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    return {
      // 密码登录表单数据
      loginForm: {
        phone: "",
        password: "",
      },
      // 表单校验规则
      loginRules: {
        phone: [
          { required: true, message: "请输入您的手机号码", trigger: "blur" },
          { validator: checkPhone, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入您的密码", trigger: "blur" },
        ],
      },
      dialogVisible: false,
      // 验证码登录表单数据
      captchaLoginForm: {
        phone: "",
        captcha: "",
        // 控制验证码输入框是否关闭
        whether: true,
      },
      append: "",
    };
  },
  methods: {
    // 登录按钮
    login() {
      // 登录之前先对表单进行预验证
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("输入不合法, 请检查您的输入项 !");
        }
        try {
          const { data: res } = await this.$http({
            url: `/login/cellphone`,
            method: "post",
            data: {
              phone: this.loginForm.phone,
              password: this.loginForm.password,
              timestamp: this.$timestamp()
            },
          });
          if (res.code === 200) {
            this.$message.success("登录成功 !");
            console.log(res)
            // 先清空sessionStorage，再保存cookie信息
            window.sessionStorage.clear();
            window.sessionStorage.setItem("userId", res.account.id)
            window.sessionStorage.setItem("cookie", res.cookie);
            // 修改登录状态
            // this.$store.commit("updateLoginState", true);
            // console.log(this.$store.state.isLogin)
            this.$router.push({ path: "/home" });
          } else {
            this.$message.error(res.msg + ", 状态码为: " + res.code);
          }
        } catch (err) {
          this.$message.error(err.response.data.message);
        }
      });
    },
    // 忘记密码按钮
    showLoginDialog() {
      // 展示对话框
      this.dialogVisible = true;
    },
    // 对话款关闭事件
    captchaDialogClosed() {
      // 重置表单
      this.$refs.captchaLoginFormRef.resetFields();
      // 清空验证码输入框
      this.captchaLoginForm.captcha = "";
      // 验证码输入框关闭
      this.captchaLoginForm.whether = true;
    },
    // 重置按钮
    reset() {
      this.$refs.loginFormRef.resetFields();
    },
    // 发送验证码
    sendCaptcha() {
      this.$refs.captchaLoginFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请输入合法的手机号码 !");
        }
        try {
          // const { data: res } = await this.$http.post('/captcha/sent',{
          //   phone:this.captchaLoginForm.phone,
          //   timestamp:this.$timestamp()
          // })
          const { data: res } = await this.$http({
            url: "/captcha/sent",
            method: "post",
            data: {
              phone: this.captchaLoginForm.phone,
              timestamp: this.$timestamp(),
            },
          });
          if (res.code === 200) {
            setTimeout(() => {
              this.$message.success("验证码已发送至您的手机, 请注意查收 !");
            }, 500);
            this.captchaLoginForm.whether = false;
          } else if (res.code === 400) {
            this.$message.error("今日验证码发送次数到达上限 !");
          } else {
            this.$message.error(res.msg + ", 状态码为: " + res.code);
          }
        } catch (err) {
          this.$message.error(err.response.data.message);
        }
      });
    },
    // 验证码登录
    captchaLogin() {
      this.$refs.captchaLoginFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("输入不合法, 请检查您的输入项 !");
        }
        try {
          // const {data: res} = await this.$http.post('/login/cellphone',{
          //   phone: this.captchaLoginForm.phone,
          //   captcha: this.captchaLoginForm.captcha,
          //   timestamp: this.$timestamp()
          // })
          const { data: res } = await this.$http({
            url: "/login/cellphone",
            method: "post",
            data: {
              phone: this.captchaLoginForm.phone,
              captcha: this.captchaLoginForm.captcha,
            },
          });
          if (res.code === 200) {
            this.$message.success("登录成功 !");
            // 先清空sessionStorage，再保存cookie信息
            window.sessionStorage.clear();
            window.sessionStorage.setItem("userId", res.account.id)
            window.sessionStorage.setItem("cookie", res.cookie);
            // 修改登录状态
            // this.$store.commit("updateLoginState", true);
            this.$router.push({ path: "/home" });
          } else {
            this.$message.error(res.msg + ", 状态码为: " + res.code);
          }
        } catch (err) {
          this.$message.error(err.response.data.message);
        }
      });
    },
    // 注册按钮
    register() {
      this.$router.push({ path: "/register" });
    },
  },
};
</script>

<style lang="less" scoped>
// 此处写样式
.login_container {
  width: 100%;
  height: 100%;
  background-image: url("../assets/tu_1.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  .login_box {
    width: 500px;
    height: 400px;
    background-image: linear-gradient(
      to top right,
      rgb(85, 95, 151),
      rgb(90, 122, 134),
      rgb(175, 61, 61),
      rgb(156, 86, 156)
    );
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 8%;
    opacity: 0.8;
    .el-form {
      position: absolute;
      bottom: 20px;
      width: 100%;
      box-sizing: border-box;
      padding: 0 40px;
      span {
        color: rgb(209, 29, 29);
        cursor: pointer;
      }
    }
    .btns {
      display: flex;
      justify-content: space-around;
      margin-top: 40px;
      .el-button {
        margin: 0 22px;
      }
    }
  }
}
</style>